const app = getApp()
const {
  api
} = require('../../../utils/api.js')
const req = require('../../../utils/req.js')

Page({
  // 页面的初始数据
  data: {
    info: {}, // 商品参数
    gallery: [], // 画廊
    attribute: [], // 商品参数
    issue: [], // 问题
    comment: [], // 评论
    productList: [], // 商品列表
    goodsList: [], // 猜你喜欢
    specificationList: [], // 商品种类
    attributeTitle: '商品参数',
    likeTitle: '猜你喜欢',
    QATitle: '问答专区',
    userName: 'xxx',
    selectedCount: 1, // 默认商品数量
    userHasCollect: 0, // 是否已收藏
    selectedAttr: [], // 是否选择规格
    token: '', // 身份ID
    close: true, // 控制规格面板的显示与隐藏
    ids: 0,
    num: 0,
    selectedInfo: {},
    goodsCount: 0, // 购物车商品数量
    specification1: '', //规格1
    specification2: '', //规格2
    newPrice: 0, // 统计商品总金额
    noCollect: '../../../images/index/goodsDetail/xingxing.png',
    yesCollect: '../../../images/index/goodsDetail/active_xingxing.png'
  },

  // 生命周期函数--监听页面加载
  onLoad: function(options) {
    let goodsId = options.id,
      goods_detail = api.goods_detail,
      goods_related = api.goods_related

    goods_detail.data.id = goodsId
    goods_related.data.id = goodsId
    // 获取商品详情数据
    req.ask(goods_detail).then(res => {
      console.log('goods_detail', res.data.data)
      let data = res.data.data
      this.setData({
        info: data.info,
        gallery: data.gallery,
        attribute: data.attribute,
        issue: data.issue,
        comment: data.comment,
        productList: data.productList,
        specificationList: data.specificationList,
        selectedAttr: Array(data.specificationList.length),
        userHasCollect: data.userHasCollect
      })
      console.log(res)
    })
    // 获取详情相关商品
    req.ask(goods_related).then(res => {
      this.setData({
        goodsList: res.data.data.goodsList
      })
    })
  },
  // 显示选择商品规格面板
  showSpecification() {
    this.setDataColse(false)
  },
  // 将商品添加到收藏列表
  goodsCollect(event) {
    console.log(this.data.token)
    if (this.data.token) {
      let collect_toggle = api.collect_toggle
      collect_toggle.data.valueId = event.currentTarget.dataset.goodsId

      req.ask(collect_toggle).then(res => {
        let userHasCollect = this.data.userHasCollect == 0 ? 1 : 0
        this.setData({
          userHasCollect
        })
        // 显示收藏列表
        req.ask(api.collect_list).then(res => {
          console.log(res)
        })
      })
    } else {
      this.goLoginPage()
      console.log('no token')
    }
  },
  // 商品添加到购物车
  addGoodToCart() {
    this.buyImmediately()

    if (this.data.token) {
      let data = {}
      if (this.data.ids) {
        this.calcMoney(this.data.ids)
        data = this.data.selectedInfo
      } else {
        let count = 0
        let productList = this.data.productList[0]
        data.productId = productList.id
        data.goodsId = productList.goods_id
        data.number = ++count
      }
      if (this.data.ids || this.data.productList.length >= 1) {
        wx.request({
          url: 'https://nideshop.bluej.cn/api/cart/add',
          method: 'post',
          data: data,
          header: {
            'content-type': 'application/json',
            'X-Nideshop-Token': this.data.token,
          },
          success: res => {
            let tempCount = 0
            wx.showToast({
              title: '添加成功'
            })
            if (res.data.errno !== 400) {
              let cartList = res.data.data.cartList
              cartList.forEach(item => {
                tempCount += item.number
              })
            } else {
              wx.showToast({
                title: '该商品已经下架了',
                icon: 'none'
              })
							return
            }
            this.setData({
              goodsCount: tempCount
            })
						console.log(tempCount, res.data)
            wx.setStorage({
              key: 'goods_count',
              data: JSON.stringify(this.data.goodsCount)
            })
          }
        })
      }

    } else { // 没有登录
      this.goLoginPage()
    }
  },
  //选择规格
  selectSpecification(event) {
    let {
      index,
      id,
      specIndex
    } = event.currentTarget.dataset
    let selectedAttr = this.data.selectedAttr
    let list = this.data.specificationList

    selectedAttr[specIndex] = id
    this.setData({
      selectedAttr,
    })
    if (this.data.num != selectedAttr.length - 1) {
      if (selectedAttr[this.data.num]) {
        this.setData({
          num: this.data.num + 1
        })
      }
    } else {
      this.setData({
        ids: selectedAttr.join('_')
      })
    }

    // 修改规格文本
    if (specIndex == 0) {
      this.setData({
        specification1: list[specIndex].valueList[index].value
      })
    } else if (specIndex == 1) {
      this.setData({
        specification2: list[specIndex].valueList[index].value
      })
    }
  },
  // 减少商品数量
  increase() {
    if (this.data.selectedCount === 1) {
      return
    } else {
      this.data.selectedCount--
        this.setData({
          selectedCount: this.data.selectedCount--
        })
    }
    if (this.data.ids) {
      this.calcMoney(this.data.ids)
    }
  },
  // 增加商品数量
  reduce() {
    this.data.selectedCount++
      this.setData({
        selectedCount: this.data.selectedCount++
      })
    if (this.data.ids) {
      this.calcMoney(this.data.ids)
    }
  },
  // 计算商品总价格
  calcMoney(ids) {
    let productList = this.data.productList
    let money = 0
    productList.forEach(item => {
      if (item.goods_specification_ids == ids) {
        money = this.data.selectedCount * item.retail_price
        if (this.data.selectedCount == 0) {
          this.data.selectedCount++
        }
        this.setData({
          newPrice: money,
          'selectedInfo.goodsId': item.id,
          'selectedInfo.number': this.data.selectedCount,
          'selectedInfo.productId': item.goods_id
        })
      }
    })
  },
  // 关闭规格面板
  closePanel() {
    this.setDataColse(true)
  },
  // 立即购买
  buyImmediately() {
    if (this.data.specificationList.length > 0) {
      this.setDataColse(false)
    }
  },
  // 设置close属性
  setDataColse(bol) {
    this.setData({
      close: bol
    })
  },
  // 页面跳转
  goHomePage() {
    app.jumpToPage('../index')
  },

  goMyCartPage() {
    app.jumpToPage('../../cart/cart')
  },

  goGoodDetail(event) {
    wx.navigateTo({
      url: './goodsDetail?id=' + event.currentTarget.dataset.id
    })
  },
  // 跳转到login页
  goLoginPage() {
    wx.showToast({
      title: '请先进行登录',
      icon: 'none',
      success: () => {
        setTimeout(() => {
          wx.navigateTo({
            url: '../../login/login'
          })
        }, 2000)
      }
    })
  },
  // 生命周期函数--监听页面显示
  onShow: function() {
    // 获取登录状态
    wx.getStorage({
      key: 'token',
      success: res => {
        this.setData({
          token: res.data
        })
      }
    })
    req.ask(api.cart_goodscount).then(res => {
      this.setData({
        goodsCount: res.data.data.cartTotal.goodsCount
      })
    })
  }
})